#!/bin/sh
action=$1
if [ -z "$action" ]
then
    echo "usage: $0 < status| stop | start | restart>"
    exit 1
fi

OS=`uname -a| cut -d\  -f1`

case $OS in
    Linux) flags="-weo";;
    *) flags="-eo";;
esac
sippid=`ps $flags pid,args|grep -i sipauthserve|grep -v 'grep'|awk '{print $1}'`
smqpid=`ps $flags pid,args|grep -v 'grep'|grep -i smqueue|awk '{print $1}'`
btspid=`ps $flags pid,args|grep -v 'grep'|grep -i OpenBTS|awk '{print $1}'`
transpid=`ps $flags pid,args|grep -v 'grep'|grep -i transceiver|awk '{print $1}'`
btshomedir=`pwd`
smqhomedir=${btshomedir}/../../../smqueue/trunk/smqueue
siphomedir=${btshomedir}/../../../subscriberRegistry/trunk
transhomedir=${btshomedir}

case "${action:?}" in
    'stop')
        echo "Stopping bts...please wait..."
        kill $sippid 2>/dev/null 
        if [ -z "$sippid" ]; then
            echo "sip authentication server is stopped."
        fi
        kill $smqpid 2>/dev/null
        if [ -z "$smqpid" ]; then
            echo "smqueue is stopped."
        fi 
        kill $btspid 2>/dev/null
        if [ -z "$btspid" ]; then
            echo "bts is stopped."
        fi
        kill $transpid 2>/dev/null 
        if [ -z "$transpid" ]; then
            echo "transceiver is stopped."
        fi
    ;;
    'start')
        if [ ! -w nohup.out ]; then
            rm -f nohup.out 2>&1   
        fi
        if [ "$sippid" ]; then
            echo "sip authentication server Already running"
        else
            nohup ${siphomedir}/sipauthserve >> ./bts.log 2>&1 &
        fi
        if [ "$smqpid" ]; then
            echo "smqueue Already running"
        else
            nohup ${smqhomedir}/smqueue >> ./bts.log 2>&1 &
        fi
        if [ "$btspid" ]; then
            echo "BTS Alread running"
        else
            ${btshomedir}/OpenBTS
        fi
        ;;
    'restart')
        $btshomedir/rc.bts stop 
        sleep 2
        $btshomedir/rc.bts start 
    ;;
    'status')
        if [ "$sippid" ]; then
            echo "sip authentication server is running, pid=$sippid"
        else
            echo "sipauthserve is not running."
        fi
        if [ "$smqpid" ]; then
            echo "smqueue is running. pid=$smqpid"
        else
            echo "smqeue is not running."
        fi
        if [ "$btspid" ]; then
            echo "bts is running. pid=$btspid"
        else
            echo "bts is not running."
        fi
    ;;
    *) echo "usage: $0 <status | stop | start | restart >"
esac
exit 0
